﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Core.IRepository;
using WebApi.Core.IRepository.Base;
using WebApi.Core.IService;
using WebApi.Core.Model.Entity;
using WebApi.Core.Service.Base;

namespace WebApi.Core.Service
{
    public class UserRoleService : BaseServices<UserRoleEntity>, IUserRoleService
    {
        private readonly IUserRepository _userDal;
        private readonly IRoleRepository _roleDal;
        private readonly IModuleRepository _moduleDal;
        private readonly IUserRoleRepository _userRoleDal;
        private readonly IRoleModuleRepository _roleModuleDal;

        public UserRoleService(IBaseRepository<UserRoleEntity> _baseRepository,

            IRoleRepository roleRepository,
            IUserRepository userDal,
            IModuleRepository moduleRepository,
            IUserRoleRepository userRoleDal,
            IRoleModuleRepository roleModuleRepository) 
            :base(_baseRepository)
        {
            _userDal = userDal;
            _roleDal = roleRepository;
            _moduleDal = moduleRepository;
            _userRoleDal = userRoleDal;
            _roleModuleDal = roleModuleRepository;
        }

        //public async Task<int> GetCount()
        //{
        //    return await _userDal.GetCount();
        //}

        /// <summary>
        /// 获取全部 角色接口(按钮)关系数据  
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserRoleEntity>> GetUserRoleByUserId(int uId)
        {
            var userRoles = await _userRoleDal.Query();
            var list = userRoles.Where(x=>x.UserId == uId).ToList();
            return list;
        }


        public async Task<string> GetUserRoleNameStr(int uId)
        {
            string roleName = "";

            var users = await _userDal.Query();
            var user = users.FirstOrDefault(x => x.UserId == uId);

            var roleList = await _roleDal.Query();
            if (user != null)
            {
                var userRoles = await _userRoleDal.Query();
                var uRoles = userRoles.Where(x => x.UserId == user.UserId).ToList();
                if (uRoles.Count > 0)
                {
                    var arr = uRoles.Select(ur => ur.RoleId).ToList();
                    var roles = roleList.Where(d => arr.Contains(d.Id));

                    roleName = string.Join(',', roles.Select(r => r.Name).ToArray());
                }
            }
            return roleName;
        }



    }
}
